package com.foodchain.service;

import com.foodchain.consts.Consts;
import com.foodchain.entity.News;
import com.foodchain.entity.NewsContent;
import com.foodchain.repository.NewsContentRepository;
import com.foodchain.repository.NewsRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class NewsService {

    @Resource
    private NewsRepository repository;

    @Resource
    private NewsContentRepository newsContentRepository;

    public Page<News> list(Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createTime");
        Page<News> all = repository.findAll(pageable);
            if (all.getContent().size() > 0) {
                for (News news : all) {
                    news.setImg(Consts.FileUrl.file_url+"/"+ news.getImg());
                }
            }

        return all;
    }

    public News queryNewsContent(String newsId) {
        News one = repository.getOne(newsId);
        NewsContent content = newsContentRepository.findByNewsId(newsId);
        if(content!=null){
            one.setContent(content.getContent());
        }
         one.setImg(Consts.FileUrl.file_url+"/"+one.getImg());
        return one;
    }
}
